const auth = require('basic-auth')
const koaJwt = require('koa-jwt')
const jwt = require('jsonwebtoken')
const User = require('../models/user')

exports.jwtAuth = koaJwt({ secret: process.env.JWT_SECRET })

exports.basicAuth = async function (ctx, next) {
  var user = auth(ctx.request)
  if (!user) {
    ctx.status = 401
    ctx.body = {
      success: false,
      message: 'basic authentication required'
    }
  } else {
    var query = await User.find(user)
    if (query.length) {
      await next()
    } else {
      ctx.status = 401
      ctx.body = {
        success: false,
        message: 'wrong username or password'
      }
    }
  }
}

exports.getToken = async function (ctx, next) {
  var name = auth(ctx.request).name
  var token = jwt.sign({ name }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRE })
  ctx.body = {
    success: true,
    message: 'success',
    data: { token }
  }
}
